package com.doitedu.day03.funcs

import scala.collection.immutable
import scala.io.Source

/**
 * @Date 22.6.22
 * @Created by HANGGE
 * @Description
 */
object _06FlattenMap方法04 {
  def main(args: Array[String]): Unit = {

    val lines = Source.fromFile("E://words.txt").getLines()
    // 文件中所有的单词   map + flatten
    val words: Iterator[String] = lines.flatMap(_.split("\\s+"))
    // a  b  a  a  c  b
    val ls = words.toList.map(_.toLowerCase)
    // (a,1)  (b,1) (a,1) (a,1)   a ->[(a,1) ,(a,1) ,(a,1) ,(a,1) ]
    val wordAndOne: immutable.Seq[(String, Int)] = ls.map(wd => {
      (wd, 1)
    })
    //a ->[(a,1) ,(a,1) ,(a,1) ,(a,1) ]
    val grouped: Map[String, immutable.Seq[(String, Int)]] = wordAndOne.groupBy(_._1)
    grouped.map(tp=>{
      val word = tp._1
      val cnt = tp._2.map(_._2).sum
      (word,cnt)
    }).foreach(println)

   /* grouped.map(tp=>{
      val word = tp._1
      val cnt = tp._2.size
      (word,cnt)
    }).foreach(println)*/
    
    /*// 统计单词的次数  [借助了Map集合的特点]
    // Java实现*/
  }
}
